import React, {lazy} from 'react';
import BaseComponent from './index';

/**
 * 高阶组件：把 BaseComponent 的能力包一层，允许外部覆盖 state/actions
 * 用法：
 *   export default withBasePage({
 *     queryApi: () => axios.post(...),
 *     deleteApi: () => axios.post(...),
 *     state: { buttons: ['query','add'] }
 *   })(YourRealPage);
 */
export default function withBasePage(options = {}) {
    return function wrap(WrappedComponent) {
        const {
            queryApi,
            deleteApi,
            dataProcess,
            modalRef,
            hasLzModal,
            state: extraState = {},
            ...restOptions
        } = options;

        return class WithBase extends BaseComponent {
            constructor(props) {
                super(props);

                // 1. 合并 state（同名时 extraState 优先生效）
                this.state = {
                    ...this.state,
                    ...extraState
                };

                // 2. 覆盖 / 注入方法
                if (queryApi) this.queryApi = queryApi;
                if (deleteApi) this.deleteApi = deleteApi;
                if (dataProcess) this.dataProcess = dataProcess;
                if (modalRef) this.modalRef = modalRef;
                if (hasLzModal) this.hasLzModal = hasLzModal;
                // this.extraContentBeforeTable = options.extraContentBeforeTable || null;
                // this.extraContentAfterTable = options.extraContentAfterTable || null;

                if (this.hasLzModal) {
                    this.LzModal = lazy(() => import('../lzModal'));
                }

                // 3. 其余字段直接挂到实例上
                Object.assign(this, restOptions);
            }

            // 4. 把 BaseComponent 渲染结果包一层，再把 this 通过 ref 传给真实组件
            render() {
                const baseUI = super.render();   // 先拿到 BaseComponent 的完整 UI
                return (
                    <>
                        {baseUI}
                        {/*{this.extraContentBeforeTable && this.extraContentBeforeTable(this)}*/}
                        {this.extraContentAfterTable && this.extraContentAfterTable(this)}
                    </>
                );
            }
        };
    };
}